window.addEvent('domready', function(){
	var form = $('frmSearch');
	
	//pagination
	new Pagination($('pagination'),{
		onPageChange: function(obj){
			form.offset.value = obj.getPageNumber()-1;
			search_cont(form);
		}
	});
	
	//table header untuk sorting
	new SortableTableHeader($('prop_table').getElement('tr[class:header]'), {
		tableFieldName:['kary_id','kary_nama','kary_status_marital','kary_email','kary_tgl_masuk'],
		onHeaderClick:function(item, fieldName, sort){
			form.orderby.value = fieldName+" "+sort;
			search_cont(form);
		}
	});
	
	search(form);
});

function search(form){
	form.set('send',{
		onSuccess: function(res){
			//table content
			var json = JSON.decode(res);
			$('prop_table_content').set('html', json.table_content);
			
			//rubah jumlah halamannya
			$('pagination').retrieve('pagination').setPageCount(Math.ceil(json.table_num_record/10));
		}
	}).send();
}

function search_cont(form){
	form.set('send',{
		onSuccess: function(res){
			//table content
			var json = JSON.decode(res);
			$('prop_table_content').set('html', json.table_content);
		}
	}).send();
}

function do_add(){
	FBModal_show2(APP.base+'/ajax/addModal', 'post', "", true, false, null, {
		onSuccess: function(res){
			$$('.datepicker').each(function(item){
				dtpicker_attach(item);
			});
			
			var check = new FormCheck('frmModal',{submitByAjax:true, submit:false, 
		        onAjaxSuccess: function(res){
					var json = JSON.decode(res);
					FBModal_message(APP.base+'/ajax/messageDialog', "Save", json.msg);
					search($('frmSearch'));
		        },
		        onValidateSuccess: function(){
		        	if ($('ginfo').getStyle('display')!='none'){
			        	$('ginfo').setStyle('display','none'); 
			        	$('cinfo').setStyle('display','block');
			        	_addRowAlamat($('cinfo_alamat'));
			        	_addRowTlp($('cinfo_tlp'));
		        	}
		        	else{
		        		check.setOptions({submit:true, submitByAjax:true});
		        	}
		        },
		    });
			$('frmModal').store('formCheck', check);
		}
	});
}

function do_delete(rowElement, id){
	ajax(APP.base+'/ajax/delete/'+id, "post", "", $empty, function(res){
		var json = JSON.decode(res);
		if (!json.error){
			//tween opacity and destroy it
			rowElement.get('tween').chain(function(){
				rowElement.destroy();
			}).start('opacity',[1,0]);
		}
		FBModal_message(APP.base+'/ajax/messageDialog', "Delete", json.msg);
		search($('frmSearch'));
	});
}

function do_edit(id){
	FBModal_show2(APP.base+'/ajax/editModal/'+id, 'post', "", true, false, null, {
		onSuccess: function(){
			$$('.datepicker').each(function(item){
				dtpicker_attach(item);
			});
			
			var check = new FormCheck('frmModal',{submitByAjax:true, submit:false, 
		        onAjaxSuccess: function(res){
					var json = JSON.decode(res);
					FBModal_message(APP.base+'/ajax/messageDialog', "Save", json.msg);
					search($('frmSearch'));
		        },
		        onValidateSuccess: function(){
		        	if ($('ginfo').getStyle('display')!='none'){
			        	$('ginfo').setStyle('display','none'); 
			        	$('cinfo').setStyle('display','block');
			        	if ($('cinfo_alamat').getChildren().length==0) _addRowAlamat($('cinfo_alamat'));
			        	if ($('cinfo_tlp').getChildren().length==0) _addRowTlp($('cinfo_tlp'));
		        	}
		        	else{
		        		check.setOptions({submit:true, submitByAjax:true});
		        	}
		        },
		    });
			$('frmModal').store('formCheck', check);
		}
	});
}

var rowAlamatIndex = 0;
function _addRowAlamat(container){
	var check = $('frmModal').retrieve('formCheck');
	var tr = new Element('tr');
	var td1 = new Element('td');
	var td2 = td1.clone();
	var td3 = td1.clone();
	
	var el1 = new Element('input',{type:"text", style:"width:400px",name:"inp[11]["+rowAlamatIndex+"][1]", class:"validate['required']"});
	var el2 = new Element('select',{style:"width:100%", name:"inp[11]["+(rowAlamatIndex++)+"][2]"});
	var el3 = new Element('a',{class:"fakeLink", html:"delete"}).addEvent('click',function(){
		check.dispose(el1);
		check.dispose(el2);
		el3.getParent('tr').destroy();
	});
	td1.grab(el1).inject(tr);
	td2.grab(el2).inject(tr);
	td3.grab(el3).inject(tr);
	tr.inject(container);
	
	check.register(el1);
	check.register(el2);
	
	//adding option kota
	ajax(APP.base+'/ajax/kotaCombo', "post", "", $empty, function(res){ el2.set('html',res); });
}

var rowTlpIndex=0;
function _addRowTlp(container){
	var check = $('frmModal').retrieve('formCheck');
	var tr = new Element('tr');
	var td = new Element('td');
	var el1 = new Element('input',{type:"text", style:"width:40px", name:"inp[12]["+rowTlpIndex+"][1]", class:"validate['required','number']"});
	var el2 = new Element('input',{type:"text", style:"width:105px", name:"inp[12]["+(rowTlpIndex++)+"][2]", class:"validate['required','number']"});
	var el3 = new Element('a',{class:"fakeLink",html:'delete'}).addEvent('click',function(){
		check.dispose(el1);
		check.dispose(el2);
		el3.getParent('tr').destroy();
	});
	tr.grab( td.clone().grab(el1) )
	.grab(td.clone().set('html','-'))
	.grab( td.clone().grab(el2) )
	.grab(td.grab(el3))
	.inject(container);
	
	
	check.register(el1);
	check.register(el2);
}

function do_addCuti(){
	var utils = APP.base.replace('/psdm/karyawan','');
	FBModal_show2(utils +'/utils/searchDialog/karyawan/getDialog', 'post', 
		"submit_action=do_addCuti_searchCallback", true, false, null, {
		onSuccess: function(res){
			Utils.searchDialog.install({
				form:'karyawanSearchFrm',
				pagination:'karyawanSearchFrm_pagination',
				table: {
					element:'karyawanSearchFrm_table',
					columns:['kary_id','kary_nama','kary_status_marital','kary_email','kary_tgl_masuk'],
					content:'karyawanSearchFrm_tableContent',
				}
			});
		}
	});
}

function do_addCuti_searchCallback(kary_id, kary_nama){
	FBModal_show2(APP.base+'/ajax/setStatusModal/'+kary_id+'/'+kary_nama, 'post', "", true, false, null, {
		onSuccess: function(res){
			var tgl1 = dtpicker_attach0($('tglMulai'), {timePicker:false, 
				onClose: function(){ 
					tgl2.options.minDate = {date: tgl1.attachTo.value, format:'Y-m-d'};
					tgl2.formatMinMaxDates();
				}
			});
			
			var tgl2 = dtpicker_attach0($('tglSelesai'), {timePicker:false,
				minDate:{date: tgl1.attachTo.value, format:'Y-m-d'},
				onClose: function(){ 
					tgl1.options.maxDate = {date: tgl2.attachTo.value, format:'Y-m-d'};
					tgl1.formatMinMaxDates();
				}
				});
			
			var check = new FormCheck('frmModal',{submitByAjax:true, submit:true, 
		        onAjaxSuccess: function(res){
					var json = JSON.decode(res);
					FBModal_message(APP.base+'/ajax/messageDialog', "Save", json.msg);
					search($('frmSearch'));
		        },
		        onSubmit:function(){
		        	var type = $$('select[name="inp[1]"]')[0].value;
		        	var revalidate = $$('.revalidate');
		        	if (type=='CT'){
		        		revalidate.each(function(item){
		        			check.register(item);
		        		});
		        	}
		        	else{
		        		revalidate.each(function(item){
		        			check.dispose(item);
		        		});
		        	}
		        }
		    });
		}
	});
}


var addJabatan = {kary_id:'',kary_nama:'',jbt_id:'',jtb_nama:''};
function do_addJabatan(){
	var utils = APP.base.replace('/psdm/karyawan','');
	FBModal_show2(utils +'/utils/searchDialog/karyawan/getDialog', 'post', 
		"submit_action=do_addJabatan_searchCallback", true, false, null, {
		onSuccess: function(res){
			Utils.searchDialog.install({
				form:'karyawanSearchFrm',
				pagination:'karyawanSearchFrm_pagination',
				table: {
					element:'karyawanSearchFrm_table',
					columns:['kary_id','kary_nama','kary_status_marital','kary_email','kary_tgl_masuk'],
					content:'karyawanSearchFrm_tableContent',
				}
			});
		}
	});
}

function do_addJabatan_searchCallback(kary_id, kary_nama){
	addJabatan.kary_id = kary_id;
	addJabatan.kary_nama = kary_nama;
	var utils = APP.base.replace('/psdm/karyawan','');
	FBModal_show2(utils +'/utils/searchDialog/jabatan/getDialog', 'post', 
		"submit_action=do_addJabatan_searchCallback2", true, false, null, {
		onSuccess: function(res){
			Utils.searchDialog.install({
				form:'jbtSearchFrm',
				pagination:'jbtSearchFrm_pagination',
				table: {
					element:'jbtSearchFrm_table',
					columns:['jbt_id','jbt_nama', 'dep_nama', 'jbt_level'],
					content:'jbtSearchFrm_tableContent',
				}
			});
		}
	});
}

function do_addJabatan_searchCallback2(jbt_id, jbt_nama){
	addJabatan.jbt_id = jbt_id;
	addJabatan.jbt_nama = jbt_nama;
	FBModal_show2(APP.base+'/ajax/setJabatanModal/'+
		addJabatan.kary_id+'/'+addJabatan.kary_nama+'/'+
		addJabatan.jbt_id+'/'+addJabatan.jbt_nama, 'post', "", true, false, null, {
		onSuccess: function(res){
			var tglMenjabat = dtpicker_attach0($('tglMenjabat'), {timePicker:false, 
				onClose: function(){ 
					tglBerhenti.options.minDate = {date: tglMenjabat.attachTo.value, format:'Y-m-d'};
					tglBerhenti.formatMinMaxDates();
				}
			});
			var tglBerhenti = dtpicker_attach0($('tglBerhenti'), {timePicker:false,
				minDate:{date: tglMenjabat.attachTo.value, format:'Y-m-d'},
				onClose: function(){ 
					tglMenjabat.options.maxDate = {date: tglBerhenti.attachTo.value, format:'Y-m-d'};
					tglMenjabat.formatMinMaxDates();
				}
				});	
			
			var check = new FormCheck('frmModal',{submitByAjax:true, submit:true, 
		        onAjaxSuccess: function(res){
					var json = JSON.decode(res);
					FBModal_message(APP.base+'/ajax/messageDialog', "Save", json.msg);
					search($('frmSearch'));
		        }
		    });
		}
	});
}

function show_historyJabatan(kary_id){
	FBModal_show2(APP.base +'/ajax/historyJabatan/'+kary_id, 'post', "", true, false, null, {
		onSuccess: function(res){
			var form = 	$('hstJbtSearchFrm');
			var func = {
				search : function(res){
					//table content
					var json = JSON.decode(res);
					$('hstJbtSearchFrm_tableContent').set('html', json.table_content);
					
					//rubah jumlah halamannya
					$('hstJbtSearchFrm_pagination').retrieve('pagination').setPageCount(Math.ceil(json.table_num_record/10));
				},
				search_cont: function(res){
					//table content
					var json = JSON.decode(res);
					$('hstJbtSearchFrm_tableContent').set('html', json.table_content);
				}
			} 
			
			//pagination
			new Pagination($('hstJbtSearchFrm_pagination'),{
				onPageChange: function(obj){
					form.offset.value = obj.getPageNumber()-1;
					form.set('send',{onSuccess:func.search_cont}).send();
				}
			});
			
			//table header untuk sorting
			new SortableTableHeader($('hstJbtSearchFrm_table').getElement('tr[class:header]'), {
				tableFieldName:['jbt_nama','kary_jbt_tgl_menjabat','kary_jbt_tgl_berhenti'],
				onHeaderClick:function(item, fieldName, sort){
					form.orderby.value = fieldName+" "+sort;
					form.set('send',{onSuccess:func.search_cont}).send();
				}
			});
			
			//key search text
			form.key.addEvent('keyup',function(){
				form.set('send',{onSuccess:func.search}).send();
			});
			
			form.set('send',{onSuccess:func.search}).send();
		}
	});
}

function show_historyCuti(kary_id){
	FBModal_show2(APP.base +'/ajax/historyCuti/'+kary_id, 'post', "", true, false, null, {
		onSuccess: function(res){
			var form = 	$('hstCutiSearchFrm');
			var func = {
				search : function(res){
					//table content
					var json = JSON.decode(res);
					$('hstCutiSearchFrm_tableContent').set('html', json.table_content);
					
					//rubah jumlah halamannya
					$('hstCutiSearchFrm_pagination').retrieve('pagination').setPageCount(Math.ceil(json.table_num_record/10));
				},
				search_cont: function(res){
					//table content
					var json = JSON.decode(res);
					$('hstCutiSearchFrm_tableContent').set('html', json.table_content);
				}
			} 
			
			//pagination
			new Pagination($('hstCutiSearchFrm_pagination'),{
				onPageChange: function(obj){
					form.offset.value = obj.getPageNumber()-1;
					form.set('send',{onSuccess:func.search_cont}).send();
				}
			});
			
			//table header untuk sorting
			new SortableTableHeader($('hstCutiSearchFrm_table').getElement('tr[class:header]'), {
				tableFieldName:['kary_cuti_jenis','kary_cuti_tgl_mulai','kary_cuti_tgl_selesai','kary_cuti_keterangan'],
				onHeaderClick:function(item, fieldName, sort){
					form.orderby.value = fieldName+" "+sort;
					form.set('send',{onSuccess:func.search_cont}).send();
				}
			});
			
			//key search text
			form.key.addEvent('keyup',function(){
				form.set('send',{onSuccess:func.search}).send();
			});
			
			form.set('send',{onSuccess:func.search}).send();
		}
	});
}
var idCheck =  {
	request: null,
	error: false,
	msg:''
};

function checkID(el){
	var error = false;
	if (idCheck.request==null){
		idCheck.request = new Request({
			method: 'post', 
			async:false,
			onSuccess: function(responseText) {
				var json = JSON.decode(responseText)
				if (json.error){
					idCheck.msg = json.msg;
				}
				idCheck.error = json.error;
			}
		});
	}
	idCheck.request.options.url = APP.base+'/ajax/validateID/'+el.value;
	idCheck.request.send('');
	if (idCheck.error) el.errors.push(idCheck.msg);
	return !idCheck.error;
}